package com.zbkj.crmeb.order.oprocess;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import com.zbkj.crmeb.chant.request.PurchaseProductRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.crmeb.core.exception.CrmebException;
import com.factory.CommonFactory;
import com.zbkj.crmeb.enums.OrderTradeTypeEnum;
import com.zbkj.crmeb.front.request.OrderCreateRequest;
import com.zbkj.crmeb.front.request.OrderPayRequest;
import com.zbkj.crmeb.front.response.OrderPayResponse;
import com.zbkj.crmeb.merchant.api.request.BuyMemberRequest;
import com.zbkj.crmeb.order.pprocess.IOrangePayOrderProcess;
import com.zbkj.crmeb.payment.service.OrderPayService;
import com.zbkj.crmeb.store.model.StoreOrder;
import com.zbkj.crmeb.store.model.StoreOrderInfo;
import com.zbkj.crmeb.store.model.StoreProductAttrValue;
import com.zbkj.crmeb.store.request.StoreAccountInfoRequest;
import com.zbkj.crmeb.store.request.StoreOrderRefundRequest;
import com.zbkj.crmeb.store.response.StoreCartResponse;
import com.zbkj.crmeb.store.service.StoreAccountInfoService;
import com.zbkj.crmeb.store.service.StoreOrderInfoService;
import com.zbkj.crmeb.store.service.StoreOrderService;
import com.zbkj.crmeb.store.utilService.OrderUtils;
import com.zbkj.crmeb.user.model.User;
import com.zbkj.crmeb.user.service.UserService;

/**
 * 汇付聚合支付
 * @author daigb
 * @date:  2022-07-18 11:15
 */
@Service("adapayDegreeOrderProcess")
public class AdapayDegreeOrderProcess extends AbstractPayOrderProcess {
    @Autowired
    private CommonFactory commonFactory;
    @Autowired
    private UserService userService;
    @Autowired
    private StoreOrderService storeOrderService;
    @Autowired
    private StoreAccountInfoService storeAccountInfoService;
    @Autowired
    private OrderPayService orderPayService;
    @Autowired
    private StoreOrderInfoService storeOrderInfoService;
    @Autowired
    private OrderUtils orderUtils;

    /**
     * 创建支付单
     */
    @Override
    public OrderPayResponse creatOrder(String key, OrderCreateRequest orderRequest, String ip) {
        IOrangePayOrderProcess payOrderProcess = commonFactory.getPayType(orderRequest.getPayType());
        // TODO DIDIOK 支付21
        return payOrderProcess.creatPayOrder(key, orderRequest, ip);

    }

    /**
     * 回调
     */
    @Override
    public void callBack(StoreOrder order) {

    }

    /**
     * 退款
     */
    @Override
    public boolean refund(StoreOrderRefundRequest request) {
        StoreOrderInfo storeOrderInfo = storeOrderInfoService.getById(request.getOrderId());
        if(null == storeOrderInfo){
            throw new CrmebException("未查到订单");
        }
        StoreOrder storeOrder = storeOrderService.getById(storeOrderInfo.getOrderId());
        if (null == storeOrder) {
            throw new CrmebException("未查到订单");
        }
        if (!storeOrder.getPaid()) {
            throw new CrmebException("未支付无法退款");
        }
        StoreAccountInfoRequest storeAccountInfoRequest = new StoreAccountInfoRequest();
        storeAccountInfoRequest.setOrderId(storeOrderInfo.getChildOrderNumber());
        storeAccountInfoRequest.setUid(storeOrder.getUid());
        storeAccountInfoRequest.setTradeType(OrderTradeTypeEnum.REFUND.getType());
        BigDecimal refundMoney = storeAccountInfoService.selectAlreadyRefundPrice(storeAccountInfoRequest);
        StoreCartResponse storeCartResponse = JSON.parseObject(storeOrderInfo.getInfo(), StoreCartResponse.class);
        StoreProductAttrValue attrInfo = storeCartResponse.getProductInfo().getAttrInfo();
        if(request.getAmount().compareTo(attrInfo.getPaidPrice()) > 0){
            throw new CrmebException("退款金额大于支付金额，请修改退款金额");
        }
        if(request.getAmount().compareTo(BigDecimal.ZERO) == 0 && request.getType() == 2){
            throw new CrmebException("补偿性退款金额需大于零");
        }
        if(request.getAmount().add(refundMoney).compareTo(attrInfo.getPaidPrice()) > 0){
            throw new CrmebException("已补偿性退款共计"+refundMoney+"元,请修改退款金额");
        }
        IOrangePayOrderProcess payOrderProcess = commonFactory.getPayType(storeOrder.getPayType());
        return payOrderProcess.refund(request, storeOrder,storeOrderInfo);
    }

    @Override
    public Map<String, Object> toPayOrder(OrderPayRequest request, String ip) {
        User currentUser = userService.getInfo();
        StoreOrder storeOrderPram = new StoreOrder();
        storeOrderPram.setOrderId(request.getUni());
        // storeOrderPram.setUid(currentUser.getUid());
        storeOrderPram.setIsDel(false);
        StoreOrder existStoreOrder = storeOrderService.getInfoByEntity(storeOrderPram);
        if (null == existStoreOrder) {
        	throw new CrmebException("商家已修改订单,请刷新");
        }
        if (existStoreOrder.getPaid()) {
        	throw new CrmebException("该订单已支付");
        }
        //生成子订单
        orderUtils.createPickingOrderInfo(existStoreOrder);
        if (0 != existStoreOrder.getStatus()) {
        	throw new CrmebException("该订单状态不正确! 请刷新后查看订单!");
        }
        // 判断支付类型是否更改
        if (!existStoreOrder.getPayType().equals(request.getPaytype())) {
            existStoreOrder.setPayType(request.getPaytype());
            boolean changePayTypeResult = changePayType(request.getPaytype(), existStoreOrder.getOrderId());
            if (!changePayTypeResult)
                throw new CrmebException("更新订单支付类型失败");
        }
        if (existStoreOrder.getPayPrice().compareTo(BigDecimal.ZERO)==0){
            HashMap<String, Object> resultMap = new HashMap<>();
            resultMap.put("result", "SUCCESS");
            resultMap.put("status", null);
            resultMap.put("data", null);
            orderPayService.afterPaySuccess(existStoreOrder);
            return resultMap;
        }
        IOrangePayOrderProcess payOrderProcess = commonFactory.getPayType(request.getPaytype());
        
    	return payOrderProcess.toPayOrder(existStoreOrder, ip);
    }

    @Override
    public Object buyMember(BuyMemberRequest request) {
        IOrangePayOrderProcess payOrderProcess = commonFactory.getPayType(request.getPayType());
        return payOrderProcess.buyMember(request);
    }

    @Override
    public Map<String, Object> purchaseProduct(PurchaseProductRequest purchaseProductRequest, String ip) {
        IOrangePayOrderProcess payOrderProcess = commonFactory.getPayType(purchaseProductRequest.getFrom());
        return payOrderProcess.purchaseProduct(purchaseProductRequest, ip);
    }

    /**
     * 更换支付类型
     * @param payType 支付类型
     */
    public boolean changePayType(String payType, String orderId) {
        StoreOrder storeOrderPram = new StoreOrder();
        storeOrderPram.setOrderId(orderId);
        StoreOrder existOrder = storeOrderService.getByEntityOne(storeOrderPram);
        if (null == existOrder)
            throw new CrmebException("未找到订单信息");
        existOrder.setPayType(payType);
        return storeOrderService.updateById(existOrder);
    }

}
